<template>
    <div class="page animate__animated animate__fadeIn">
        <el-card :bordered="false" shadow="never" class="ivu-mt" :body-style="{ padding: '20px 20px' }">
            <el-page-header @back="goBack" :content="goods_id ? '编辑商品' : '添加商品'"></el-page-header>
        </el-card>
        <el-card :bordered="false" shadow="never" class="ivu-mt" :body-style="{ padding: '5px 20px 20px' }"
            v-loading="loadingPage">
            <el-tabs v-model="tabsActiveName">
                <el-tab-pane label="基础信息" name="0"></el-tab-pane>
                <el-tab-pane label="商品属性" name="1"></el-tab-pane>
                <!-- <el-tab-pane label="商品详情" name="2"></el-tab-pane> -->
                <!-- <el-tab-pane label="其他设置" name="3"></el-tab-pane> -->
            </el-tabs>
            <el-form size="small" label-width="100px" class="form-con" :model="goodsForm" :rules="rules"
                ref="goodsForm">
                <!-- 基础信息 -->
                <div class="form-wrap" v-show="tabsActiveName === '0'">
                    <el-form-item label="商品名称" prop="goods_name">
                        <el-input placeholder="请输入商品名称" class="form-input" v-model="goodsForm.goods_name"></el-input>
                    </el-form-item>
                    <el-form-item label="商品分类" prop="categoryIds">
                        <el-cascader v-model="goodsForm.categoryIds" :options="cateGoryList" :clearable="true" :props="{
                            label: 'name',
                            value: 'category_id',
                            checkStrictly: true
                        }" ref="cascader" placeholder="请选择上级分类" class="form-input"></el-cascader>
                        <!-- <p class="toolTip">请先选择分公司，再选择分类</p> -->
                    </el-form-item>
                    <el-form-item label="商品轮播图" prop="images">
                        <upload-multiple-image @imageHandle="getImages" :imgList="slideImg"></upload-multiple-image>
                        <div class="titTip">
                            建议尺寸：750*750，默认首张图为主图，最多上传10张
                        </div>
                    </el-form-item>
                    <el-form-item label="商品产地" prop="producer">
                        <el-input placeholder="请输入商品产地" class="form-input" v-model="goodsForm.producer"></el-input>
                    </el-form-item>
                    <el-form-item label="商品排序" prop="sort">
                        <el-input-number v-model="goodsForm.sort" controls-position="right"></el-input-number>
                    </el-form-item>
                    <!-- <el-form-item label="商品状态">
                        <el-radio-group v-model="goodsForm.status">
                            <el-radio :label="10">上架</el-radio>
                            <el-radio :label="20">下架</el-radio>
                        </el-radio-group>
                    </el-form-item> -->
                    <el-form-item v-if="clickType == 1">
                        <el-button type="primary" @click="toNext('1')">下一步</el-button>
                        <el-button type="primary" @click="submitForm('goodsForm')" :disabled="isDisabled"
                            :loading="isLoading" v-if="goods_id">提交</el-button>
                    </el-form-item>
                </div>
                <!-- 规格库存 -->
                <div class="form-wrap" v-show="tabsActiveName === '1'">
                    <!-- <el-form-item label="商品规格" props="spec_type">
                        <el-radio-group v-model="goodsForm.spec_type" disabled v-if="goods_id">
                            <el-radio :label="10">单规格</el-radio>
                            <el-radio :label="20">多规格</el-radio>
                        </el-radio-group>
                        <el-radio-group v-model="goodsForm.spec_type" @input="switchSpec" v-else>
                            <el-radio :label="10">单规格</el-radio>
                            <el-radio :label="20">多规格</el-radio>
                        </el-radio-group>
                    </el-form-item> -->
                    <!-- 单规格 -->
                    <div class="single-wrap" v-if="goodsForm.spec_type == 10">
                        <el-form-item label="平台价" prop="goods_price">
                            <el-input v-model="goodsForm.goods_price" class="form-input" placeholder="请输入平台价"
                                oninput="value = value.replace(/[^\d|\.]/g, '')"></el-input>
                        </el-form-item>
                        <el-form-item label="销售价" prop="market_price">
                            <el-input v-model="goodsForm.market_price" class="form-input" placeholder="请输入销售价"
                                oninput="value = value.replace(/[^\d|\.]/g, '')"></el-input>
                        </el-form-item>
                        <el-form-item label="库存" prop="stock_num">
                            <el-input v-model="goodsForm.stock_num" class="form-input" placeholder="请输入当前商品库存"
                                type="number"></el-input>
                        </el-form-item>
                        <el-form-item label="单位" prop="goods_unit">
                            <el-input v-model="goodsForm.goods_unit" class="form-input" placeholder="请输入单位"></el-input>
                        </el-form-item>
                        <el-form-item label="最低起卖数量" prop="minimum">
                            <el-input v-model="goodsForm.minimum" class="form-input" placeholder="请输入最低起卖数量"
                                type="number"></el-input>
                        </el-form-item>
                        <el-form-item label="商品编码">
                            <el-input v-model="goodsForm.goods_no" class="form-input"
                                placeholder="请输入当前商品编码，非必填"></el-input>
                        </el-form-item>
                    </div>
                    <!-- 多规格 -->
                    <div class="multiple-wrap" v-else>
                        <el-form-item label="规格信息">
                            <p class="toolTip" style="padding:5px 0 12px">最多添加3个商品规格组，生成的SKU数量不能超出50个</p>
                            <!-- 添加规格组 -->
                            <div class="spec-wrap" v-for="(item, index) in skuData.specList" :key="index">
                                <el-form-item label="规格名" label-width="60px">
                                    <el-input placeholder="请输入规格名" autocomplete v-model="item.spec_name" @input="(val) => {
                                        onChangeSpecGroupIpt(
                                            val,
                                            index
                                        );
                                    }
                                        "></el-input>
                                </el-form-item>
                                <el-form-item label="规格值" label-width="60px">
                                    <div class="spec-tags">
                                        <el-tag class="spec-tags-item" closable v-for="(cItem, i) in item.valueList"
                                            :key="i" @close="removeSkuAttr(index, i)">{{ cItem.spec_value }}</el-tag>
                                        <el-button size="small" icon="el-icon-plus"
                                            @click="addSkuAttr(index)">添加</el-button>
                                    </div>
                                </el-form-item>
                                <div class="del-btn" @click="removeSkuGroup(index)">
                                    <i class="el-icon-error"></i>
                                </div>
                            </div>
                            <el-button icon="el-icon-plus" @click="addSkuGroup()"
                                v-if="skuData.specList.length < 3">添加规格组</el-button>
                        </el-form-item>
                        <!-- 批量设置-->
                        <el-form-item label="批量设置" v-if="skuData.skuList.length > 0">
                            <el-table :data="defaultSkuItemData" border size="small">
                                <el-table-column label="图片" width="105px">
                                    <template slot-scope="scope">
                                        <uploadSingleImg :imgUrl="scope.row.image" @handleSuccess="setDefaultImg">
                                        </uploadSingleImg>
                                    </template>
                                </el-table-column>
                                <el-table-column label="平台价">
                                    <template slot-scope="scope">
                                        <el-input v-model="scope.row.goods_price"
                                            oninput="value = value.replace(/[^\d|\.]/g, '')"></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column label="销售价">
                                    <template slot-scope="scope">
                                        <el-input v-model="scope.row.market_price"
                                            oninput="value = value.replace(/[^\d|\.]/g, '')"></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column label="库存数量">
                                    <template slot-scope="scope">
                                        <el-input v-model="scope.row.stock_num" type="number"></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column label="单位">
                                    <template slot-scope="scope">
                                        <el-input v-model="scope.row.goods_unit"></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column label="最低起卖数量">
                                    <template slot-scope="scope">
                                        <el-input v-model="scope.row.minimum" type="number"></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column label="SKU编码">
                                    <template slot-scope="scope">
                                        <el-input placeholder="sku编码" v-model="scope.row.goods_sku_no" />
                                    </template>
                                </el-table-column>
                                <el-table-column label="操作" fixed="right" width="120px">
                                    <template slot-scope="scope">
                                        <el-button type="primary" size="small" @click="handleSkuBatch">立即设置</el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </el-form-item>
                        <!-- SKU列表 -->
                        <el-form-item label="SKU列表" v-if="isInputAtrr && skuData.specList.length > 0">
                            <div class="sku-list">
                                <el-table border header-cell-class-name="header-cell" size="small"
                                    :data="skuData.skuList" :span-method="spanMethod">
                                    <el-table-column :prop="item.prop" :label="item.spec_name" v-for="(
                                            item, index
                                        ) in skuData.specList" :key="index"></el-table-column>
                                    <el-table-column prop="image" label="预览图" width="105px">
                                        <template slot-scope="scope">
                                            <uploadSingleImg :imgUrl="scope.row.image"
                                                @handleSuccess="setSpecImg(scope.$index, $event)"></uploadSingleImg>
                                        </template>
                                    </el-table-column>
                                    <el-table-column prop="goods_price" label="平台价" width="160px">
                                        <template slot-scope="scope">
                                            <el-input v-model="scope.row.goods_price"
                                                @change="setSpecGoodsPrice(scope.$index, $event)"
                                                oninput="value = value.replace(/[^\d|\.]/g, '')"></el-input>
                                        </template>
                                    </el-table-column>
                                    <el-table-column prop="market_price" label="销售价" width="160px">
                                        <template slot-scope="scope">
                                            <el-input v-model="scope.row.market_price"
                                                @change="setSpecMarketPrice(scope.$index, $event)"
                                                oninput="value = value.replace(/[^\d|\.]/g, '')"></el-input>
                                        </template>
                                    </el-table-column>
                                    <el-table-column prop="stock_num" label="库存数量" width="160px">
                                        <template slot-scope="scope">
                                            <el-input v-model="scope.row.stock_num"
                                                @change="setSpecStock(scope.$index, $event)" type="number"></el-input>
                                        </template>
                                    </el-table-column>
                                    <el-table-column prop="goods_unit" label="单位" width="160px">
                                        <template slot-scope="scope">
                                            <el-input v-model="scope.row.goods_unit"
                                                @change="setSpecUnit(scope.$index, $event)"></el-input>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="最低起卖数量">
                                        <template slot-scope="scope">
                                            <el-input v-model="scope.row.minimum"
                                                @change="setSpecMinimum(scope.$index, $event)" type="number"></el-input>
                                        </template>
                                    </el-table-column>
                                    <el-table-column prop="goods_sku_no" label="SKU编码">
                                        <template slot-scope="scope">
                                            <el-input v-model="scope.row.goods_sku_no"
                                                @change="setSpecSkuNo(scope.$index, $event)"></el-input>
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </div>
                        </el-form-item>
                    </div>
                    <el-form-item v-if="clickType == 1">
                        <template>
                            <el-button @click="toLast('0')">上一步</el-button>
                            <!-- <el-button type="primary" @click="toNext('2')">下一步</el-button> -->
                        </template>
                        <!-- <el-button type="primary" @click="submitForm('goodsForm')" :disabled="isDisabled" :loading="isLoading" v-if="goods_id">提交</el-button> -->
                        <el-button type="primary" @click="submitForm('goodsForm')" :disabled="isDisabled"
                            :loading="isLoading">提交</el-button>
                    </el-form-item>
                </div>
                <!-- 商品详情 -->
                <div class="form-wrap" v-if="tabsActiveName === '2'">
                    <el-form-item label="商品详情" prop="content">
                        <my-editor :htmlData="goodsForm.content" @getHtml="getHtml"></my-editor>
                    </el-form-item>
                    <el-form-item v-if="clickType == 1">
                        <template>
                            <el-button @click="toLast('1')">上一步</el-button>
                            <el-button type="primary" @click="toNext('3')">下一步</el-button>
                        </template>
                        <el-button type="primary" @click="submitForm('goodsForm')" :disabled="isDisabled"
                            :loading="isLoading" v-if="goods_id">提交</el-button>
                    </el-form-item>
                </div>
                <!-- 其他设置（选择关联商品） -->
                <div class="form-wrap" v-show="tabsActiveName === '3'">
                    <el-form-item label="选择关联商品">
                        <div class="upload-img-wrap">
                            <template v-if="relationGoods.length > 0">
                                <div class="pictrue upload-img-item" v-for="(item, index) in relationGoods"
                                    :key="index">
                                    <el-image :src="item.goods_image" fit="contain" class="upload-img">
                                        <div slot="error" class="image-slot">
                                            <p>暂无图片</p>
                                        </div>
                                    </el-image>
                                    <i class="el-icon-error close-icon" @click="delSelectGoods(index)"></i>
                                </div>
                            </template>
                            <div class="upLoad upload-img-item" @click="selectRelGoods">
                                <i class="el-icon-picture-outline" style="font-size: 24px"></i>
                            </div>
                        </div>
                    </el-form-item>
                    <el-form-item v-if="clickType == 1">
                        <el-button @click="toLast('2')">上一步</el-button>
                        <el-button type="primary" @click="submitForm('goodsForm')" :disabled="isDisabled"
                            :loading="isLoading">提交</el-button>
                    </el-form-item>
                </div>
            </el-form>
        </el-card>
        <select-goods-modal ref="relGoodsModal" :selectionGoodsIds="relationGoods"
            @getSelectGoods="getSelectGoods"></select-goods-modal>
    </div>
</template>
<script>
import uploadMultipleImage from "@/components/uploadMultipleImage.vue";
import uploadSingleImg from "@/components/uploadSingleImg.vue";
import selectGoodsModal from '@/components/selectGoodsModal.vue'
import myEditor from "@/components/myEditor.vue";
import { getCompanyData } from "@/api/setting.js";
import debounce from "@/utils/debounce.js";
import {
    cateGoryList,
    addGoods,
    editGoods,
    getGoodsDetail,
    goodsStockUpdate
} from "../../api/goods";
import _ from 'lodash'
export default {
    components: {
        uploadMultipleImage,
        uploadSingleImg,
        myEditor,
        selectGoodsModal
    },
    data() {
        return {
            goods_id: "",
            clickType: 1,
            applyStatus: 10,
            isDisabled: false,
            isLoading: false,
            loadingPage: false,
            tabsActiveName: "0",
            cateGoryList: [],
            goodsForm: {
                goods_name: "",
                categoryIds: "",
                images: [],
                company_id: "",
                producer: "",
                // status: 10,
                sort: 100,

                content: "",

                spec_type: 10, // 10 单规格 20 多规格

                //单规格
                goods_price: "0",
                market_price: "0",
                stock_num: "9999",
                goods_unit: "",
                minimum: "1",
                goods_no: '',

                rel_goods_id: '',

                pinyin_str: '',
                goods_initial: '',
            },
            slideImg: [],
            //多规格数据操作
            skuData: {
                specList: [],
                skuList: [],
            },
            //选择关联商品
            relationGoods: [],
            isInputAtrr: false,
            defaultSkuItemData: [{
                image: "",
                goods_price: '',
                market_price: '',
                stock_num: "9999",
                goods_unit: "",
                minimum: 1,
                goods_sku_no: "",
            }],
            rules: {
                goods_name: [
                    {
                        required: true,
                        message: "请输入商品名称",
                        trigger: "blur",
                    },
                ],
                company_id: [
                    {
                        required: true,
                        message: "请选择分公司",
                        trigger: "blur",
                    },
                ],
                categoryIds: [
                    {
                        required: true,
                        message: "请选择商品分类",
                        trigger: "change",
                        type: "array",
                        min: "1",
                    },
                ],
                images: [
                    {
                        required: true,
                        message: "请上传商品轮播图",
                        type: "array",
                        trigger: "change",
                    },
                ],
                producer: [
                    {
                        required: true,
                        message: "请输入商品名称",
                        trigger: "blur",
                    },
                ],
                goods_price: [
                    {
                        required: true,
                        message: "请输入平台价",
                        trigger: "blur",
                    },
                ],
                market_price: [
                    {
                        required: true,
                        message: "请输入销售价",
                        trigger: "blur",
                    },
                ],
                stock_num: [
                    {
                        required: true,
                        message: "请输入当前商品库存",
                        trigger: "blur",
                    },
                ],
                goods_unit: [
                    {
                        required: true,
                        message: "请输入单位",
                        trigger: "blur",
                    },
                ],
                content: [
                    {
                        required: true,
                        message: "请输入商品详情",
                        trigger: "blur",
                    },
                ],
            },
            handleType: '',
            goodsStockList: [],//审核状态下只能操作库存
        };
    },
    created() {
        this.goods_id = this.$route.query.id ? this.$route.query.id : "";
        this.clickType = this.$route.query.type ? this.$route.query.type : 1;
        this.getCateGoryList();
        if (this.goods_id) {
            this.loadingPage = true;
            this.getGoodsDetail();
            this.handleType = 'edit';
        } else {
            this.handleType = 'create'
        }
    },
    methods: {
        /**
         * 编辑商品
         * getGoodsDetail 获取商品信息
         * setGoodsData 设置商品信息
         */
        getGoodsDetail() {
            getGoodsDetail({
                goods_id: this.goods_id,
                goods_type: 20,
            }).then((res) => {
                this.loadingPage = false;
                if (res.code == 0) {
                    this.applyStatus = res.data.apply_status;
                    this.setGoodsData(res.data);
                }
            });
        },
        setGoodsData(data) {
            this.goodsForm.goods_name = data.goods_name;
            this.goodsForm.company_id = data.company_id;
            this.goodsForm.categoryIds = data.categoryIds;
            this.goodsForm.images = data.images;
            //格式化轮播图
            // this.slideImg = data.images
            for (let i = 0; i < data.images.length; i++) {
                const obj = {
                    url: data.images[i]
                }
                this.slideImg.push(obj)
            }
            this.goodsForm.sort = data.sort;
            this.goodsForm.producer = data.producer;
            this.goodsForm.content = data.content;
            this.goodsForm.spec_type = data.spec_type;
            if (data.spec_type == 10) {
                this.goodsForm.goods_price = data.goods_price;
                this.goodsForm.market_price = data.market_price;
                this.goodsForm.stock_num = data.stock_total;
                this.goodsForm.goods_unit = data.goods_unit;
                this.goodsForm.minimum = data.minimum;
                this.goodsForm.goods_no = data.goods_no;
                this.goodsForm.goods_sku_id = data.skuList[0].id;
            } else {
                this.setMultipleData(data.specList, data.skuList)
            }
            this.relationGoods = data.rel_good_arr;
        },
        //编辑商品详情的时候 整理规格数据
        setMultipleData(specList = [], skuList = []) {
            this.skuData.specList = _.cloneDeep(specList);
            this.skuData.skuList = _.cloneDeep(skuList);
            specList.forEach((v, i) => {
                v.prop = `spec_value_${i}`
            })
            let newSkuList = [];
            let cartesianList = this.cartesianProductOfSkus(specList);
            this.skuData.specList = specList;
            this.buildSkuList(cartesianList)
            this.isInputAtrr = true;
        },
        toNext(num) {
            switch (Number(this.tabsActiveName)) {
                case 0:
                    if (!this.goodsForm.goods_name) {
                        this.$message.error("基础信息-请填写商品名称");
                    } else if (!this.goodsForm.categoryIds) {
                        this.$message.error("基础信息-请选择商品分类");
                    } else if (!this.goodsForm.images.length > 0) {
                        this.$message.error("基础信息-请上传商品轮播图");
                    } else if (!this.goodsForm.producer) {
                        this.$message.error("基础信息-请输入商品产地");
                    } else {
                        this.tabsActiveName = num;
                    }
                    break;
                case 1:
                    if (this.goodsForm.spec_type == 10) {
                        if (!this.goodsForm.goods_price) {
                            this.$message.error("规格库存-请填写平台价");
                        } else if (!this.goodsForm.market_price) {
                            this.$message.error("规格库存-请填写销售价");
                        } else if (!this.goodsForm.stock_num) {
                            this.$message.error("规格库存-请填写库存");
                        } else {
                            this.tabsActiveName = num;
                        }
                    } else {
                        let skuList = this.skuData.skuList;
                        let specList = this.skuData.specList;
                        console.log('specList', specList)
                        var specFlag = specList.every(function (a, b, c) {
                            return a.spec_name != '';
                        })
                        var valueFlag = specList.every(function (a, b, c) {
                            return a.valueList.length != 0;
                        })
                        if (!specFlag) {
                            this.$message.error('规格组名称不能为空！')
                            return;
                        }
                        console.log('valueFlag', valueFlag)
                        if (!valueFlag) {
                            this.$message.error('规格值名称不能为空！')
                            return;
                        }
                        if (this.skuData.skuList.length == 0) {
                            this.$message.error('请添加规格信息！')
                            return;
                        }
                        if (this.skuData.skuList.length == 0) {
                            this.$message.error('请添加规格信息！')
                            return;
                        }
                        var goodsPriceFlag = skuList.every(function (a, b, c) {
                            return a.goods_price != '';
                        })
                        var marketPriceFlag = skuList.every(function (a, b, c) {
                            return a.market_price != '';
                        })
                        var unitFlag = skuList.every(function (a, b, c) {
                            return a.goods_unit != '';
                        })
                        if (!goodsPriceFlag) {
                            this.$message.error('请填写平台价！')
                            return;
                        }
                        if (!marketPriceFlag) {
                            this.$message.error('请填写商品销售价！')
                            return;
                        }
                        if (!unitFlag) {
                            this.$message.error('请填写商品单位！')
                            return;
                        }
                        this.tabsActiveName = num;
                    }
                    break;
                case 2:
                    if (!this.goodsForm.content) {
                        this.$message.error("商品详情-请填写商品详情");
                    } else {
                        this.tabsActiveName = num;
                    }
                    break;
            }
        },
        toLast(num) {
            this.tabsActiveName = num;
        },
        /**
         * 添加商品 选择分类系列操作
         * handleSelect 获取company_id 用来切换分类
         * getCateGoryList 获取分类列表
         */
        getCateGoryList() {
            cateGoryList({
                status: "-1",
                company_id: this.goodsForm.company_id,
            }).then((res) => {
                this.isLoading = false;
                if (res.code == 0) {
                    // res.data.forEach(v => {
                    //     if (!v.children) {//一级下面没有子元素
                    //         v.disabled = true;
                    //     } else {
                    //         v.children.forEach(item => {
                    //             if (!item.children) {
                    //                 item.disabled = true;
                    //             }
                    //         })
                    //     }
                    // })
                    this.cateGoryList = res.data;
                }
            });
        },
        /**
         * 添加商品 上传图片系列操作
         * getImages 获取上传图片数组
         */
        getImages(arr) {
            this.goodsForm.images = arr;
        },
        /**
         * 添加商品 商品详情系列操作
         * getHtml 获取富文本内容
         */
        getHtml(html) {
            this.goodsForm.content = html;
        },
        /**
         * 添加商品 规格系列操作
         * switchSpec 切换规格
         */
        switchSpec(e) {
            this.goodsForm.spec_type = e;
        },
        /*
         * 多规格操作
         * addSkuGroup 添加规格组
         * removeSkuGroup 删除规格组
         * addSkuAttr 添加规格属性值
         * removeSkuAttr 删除规格属性值
         * setDefaultImg 批量设置图片
         * handleSkuBatch 批量设置规格值
         * onChangeSpecGroupIpt 输入规格名时，给table表格做联动
         * spanMethod 合并单元行
         * cartesianProductOfSkus 笛卡尔积算法整合出所有规格的可能性
         */
        // 生成skuList
        buildSkuList(cartesianList) {
            console.log('cartesianList ------> buildSkuList方法', cartesianList)
            // 生成新的skuList
            const newSkuList = []
            for (let i = 0; i < cartesianList.length; i++) {
                const newSkuItem = {
                    ...this.defaultSkuItemData[0],
                    ...cartesianList[i]
                }
                newSkuList.push(newSkuItem)
            }
            // 兼容旧的sku数据
            this.skuData.skuList = this.oldSkuList(newSkuList)
            console.log('buildSkuList -----> this.skuData.skuList ', this.skuData.skuList)
        },
        // 合并已存在的sku数据
        oldSkuList(newSkuList) {
            // const oldSkuList = _.cloneDeep(this.multiSpecData.skuList)
            const oldSkuList = this.skuData.skuList.concat()
            console.log('oldSkuList', oldSkuList)
            console.log('newSkuList', newSkuList)
            if (!oldSkuList.length || !newSkuList.length) {
                return newSkuList
            }
            for (const index in newSkuList) {
                // 查找符合的旧记录
                let oldSkuItem = {}
                if (oldSkuList.length === newSkuList.length) {
                    oldSkuItem = _.cloneDeep(oldSkuList[index])
                } else {
                    console.log('长度不相等')
                    if (this.skuData.specList.length == 1) {
                        // oldSkuList
                    }
                    oldSkuItem = oldSkuList.find(item => {
                        console.log('oldSkuItem.skuKey', item.skuKey)
                        return item.skuKey === newSkuList[index].skuKey
                    })
                    console.log('newSkuList[index].skuKey', newSkuList[index].skuKey)
                }
                console.log('newSkuList[index]', newSkuList[index])
                console.log('oldSkuItem', oldSkuItem)
                // 写入新纪录
                if (oldSkuItem) {
                    newSkuList[index] = {
                        ...newSkuList[index],
                        ..._.pick(oldSkuItem, Object.keys(this.defaultSkuItemData[0]))
                    }
                }
            }
            return newSkuList
        },
        addSkuGroup(i) {
            this.skuData.specList.push({
                spec_name: "", //规格名  spec_name:'颜色'
                prop: "", //SKU table 展示 需用到的
                valueList: [], //当前规格下的属性值，以数组形式展开
            });
        },
        removeSkuGroup(i) {
            this.$confirm('此操作将删除选中商品, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.skuData.specList.splice(i, 1);
                this.skuData.specList.forEach((v, n) => {
                    v.prop = `spec_value_${n}`;
                    v.key = n;
                });
                console.log('删除规格组 ---》this.skuData.specList', this.skuData.specList)
                if (this.skuData.specList.length == 0) {
                    this.skuData.skuList = [];
                } else {
                    let cartesianList = this.cartesianProductOfSkus(this.skuData.specList);
                    this.buildSkuList(cartesianList)
                }
            })
        },
        addSkuAttr(i) {
            console.log('addSkuAttr 索引', i);
            this.$prompt("请输入规格值", "添加规格值", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                inputPattern: /\S+/,
                inputErrorMessage: "规格值不能为空",
                closeOnClickModal: false,
            }).then(({ value }) => {
                let specList = this.skuData.specList;
                specList[i].valueList.push({
                    spec_value: value,
                    groupKey: i,
                });
                specList[i].valueList.forEach((v, index) => {
                    v.key = index;
                });
                this.skuData.specList = specList;
                let cartesianList = this.cartesianProductOfSkus(specList);
                this.buildSkuList(cartesianList)
            });
        },
        removeSkuAttr(a, b) {
            console.log('a', a)
            console.log('b', b)
            console.log('this.skuData.specList[a].valueList[b]', this.skuData.specList[a].valueList[b])
            this.$confirm('此操作将删除选中商品, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                //修改后的代码
                let oldSpecList = _.cloneDeep(this.skuData.specList);
                let specList = this.skuData.specList;
                specList[a].valueList.splice(b, 1);
                if (specList[a].valueList.length == 0) {
                    specList.splice(a, 1);
                    if (specList.length < oldSpecList.length) {
                        let cartesianList = this.cartesianProductOfSkus(this.skuData.specList);
                        this.buildSkuList(cartesianList)
                        this.skuData.skuList.forEach(v => {
                            v.goods_price = ''
                            v.goods_sku_no = ''
                            v.image = ''
                            v.market_price = ''
                            v.skuKey = ''
                            v.skuKeys = []
                            v.stock_num = '9999'
                            v.goods_unit = ''
                            v.id = ''
                        })
                    }
                } else {
                    let cartesianList = this.cartesianProductOfSkus(this.skuData.specList);
                    this.buildSkuList(cartesianList)
                }
                this.skuData.specList = specList;
                if (specList.length == 0) {
                    this.skuData.skuList = [];
                }
            })
        },
        onChangeSpecGroupIpt(val, index) {
            debounce(() => {
                this.skuData.specList[index].spec_name = val;
                this.skuData.specList[index].prop = `spec_value_${index}`;
                this.skuData.specList[index].key = index;
                this.isInputAtrr = true;
            });
        },
        buildNewSkuList(cartesianList) {
            // 生成新的skuList
            const newSkuList = [];
            for (let i = 0; i < cartesianList.length; i++) {
                const newSkuItem = {
                    ...this.defaultSkuItemData[0],
                    ...cartesianList[i],
                };
                newSkuList.push(newSkuItem);
            }
            return newSkuList;
        },
        setSpecImg(index, e) {
            let skuList = this.skuData.skuList;
            skuList[index].image = e;
            this.skuData.skuList = skuList;
        },
        setSpecGoodsPrice(index, e) {
            this.skuData.skuList[index].goods_price = e;
        },
        setSpecMarketPrice(index, e) {
            debounce(() => {
                this.skuData.skuList[index].market_price = e;
            });
        },
        setSpecStock(index, e) {
            debounce(() => {
                this.skuData.skuList[index].stock_num = e;
            });
        },
        setSpecUnit(index, e) {
            debounce(() => {
                this.skuData.skuList[index].goods_unit = e;
            });
        },
        setSpecMinimum(index, e) {
            debounce(() => {
                this.skuData.skuList[index].minimum = e;
            });
        },
        setSpecSkuNo(index, e) {
            debounce(() => {
                this.skuData.skuList[index].goods_sku_no = e;
            });
        },
        setDefaultImg(e) {
            this.defaultSkuItemData[0].image = e;
        },
        handleSkuBatch() {
            const defaultSkuItemData = this.defaultSkuItemData[0],
                skuList = this.skuData.skuList;
            skuList.forEach((v) => {
                if (defaultSkuItemData.image) {
                    v.image = defaultSkuItemData.image;
                }
                if (defaultSkuItemData.goods_price) {
                    v.goods_price = defaultSkuItemData.goods_price;
                }
                if (defaultSkuItemData.market_price) {
                    v.market_price = defaultSkuItemData.market_price;
                }
                if (defaultSkuItemData.stock_num) {
                    v.stock_num = defaultSkuItemData.stock_num;
                }
                if (defaultSkuItemData.goods_unit) {
                    v.goods_unit = defaultSkuItemData.goods_unit;
                }
                if (defaultSkuItemData.minimum) {
                    v.minimum = defaultSkuItemData.minimum;
                }
                if (defaultSkuItemData.goods_sku_no) {
                    v.goods_sku_no = defaultSkuItemData.goods_sku_no;
                }
            });
            this.skuData.skuList = skuList;
            this.defaultSkuItemData[0].image = '';
            this.defaultSkuItemData[0].goods_price = '';
            this.defaultSkuItemData[0].market_price = '';
            this.defaultSkuItemData[0].stock_num = '9999';
            this.defaultSkuItemData[0].goods_unit = '';
            this.defaultSkuItemData[0].minimum = '';
            this.defaultSkuItemData[0].goods_sku_no = '';
        },
        cartesianProductOfSkus(skus) {
            function descriptorToObject(descriptor) {
                let attrObj = {};
                let skuKeys = [];
                let skuSelectKeyArr = [];
                let skuKey = "";
                descriptor.forEach((attrValueObj, index) => {
                    var skuKeyObj = {
                        groupKey: attrValueObj.groupKey,
                        valueKey: attrValueObj.key,
                    };
                    var skuSelectKey = attrValueObj.key;
                    skuKeys.push(skuKeyObj);
                    skuSelectKeyArr.push(skuSelectKey);
                    skuKey = skuSelectKeyArr.join("_");
                    attrObj[skus[index].prop] = attrValueObj.spec_value;
                });
                attrObj.skuKeys = skuKeys
                attrObj.skuKey = skuKey
                return attrObj
            }
            function cartesianProduct(a) {
                if (a.length === 0) return [[]];

                let result = [];
                let rest = cartesianProduct(a.slice(1));
                for (let i = 0; i < a[0].length; i++) {
                    for (let j = 0; j < rest.length; j++) {
                        result.push([a[0][i]].concat(rest[j]));
                    }
                }
                return result;
            }
            let descriptors = skus.map((sku) => sku.valueList);
            let combos = cartesianProduct(descriptors);
            return combos.map(descriptorToObject);
        },
        spanMethod({ row, column, rowIndex, columnIndex }) {
            const fields = ["spec_value_0", "spec_value_1"];
            // 当前行的数据
            const cellValue = row[column.property];
            // 判断只合并定义字段的列数据
            if (cellValue && fields.includes(column.property)) {
                const prevRow = this.skuData.skuList[rowIndex - 1]; //上一行数据
                let nextRow = this.skuData.skuList[rowIndex + 1]; //下一行数据
                // 当上一行的数据等于当前行数据时，当前行单元格隐藏
                if (prevRow && prevRow[column.property] === cellValue) {
                    return {
                        rowspan: 0,
                        colspan: 0,
                    };
                } else {
                    // 反之，则循环判断若下一行数据等于当前行数据，则当前行开始进行合并单元格
                    let countRowspan = 1; //用于合并计数多少单元格
                    while (nextRow && nextRow[column.property] === cellValue) {
                        nextRow =
                            this.skuData.skuList[++countRowspan + rowIndex];
                    }
                    if (countRowspan > 1) {
                        return {
                            rowspan: countRowspan,
                            colspan: 1,
                        };
                    }
                }
            }
        },
        /**
         * 选择关联商品
         * selectRelGoods 
         * getSelectGoods 获取选中商品
         * unique对象数组去重
         */
        selectRelGoods() {
            this.$refs.relGoodsModal.show();
            this.$refs.relGoodsModal.isLoading = true;
            this.$refs.relGoodsModal.getGoodsList()
        },
        getSelectGoods(val) {
            this.relationGoods = val;
            // this.relationGoods = this.unique(this.relationGoods.concat(val));
        },
        delSelectGoods(i) {
            this.relationGoods.splice(i, 1);
        },
        unique(arr) {
            const res = new Map();
            return arr.filter((arr) => !res.has(arr.goods_id) && res.set(arr.goods_id, 1));
        },
        /**
         * 添加商品 提交商品系列操作
         * submitForm
         */
        async submitForm(formName) {
            var submitApi, skuDataStr;
            var submitApi, skuDataStr;
            if (this.goods_id) {
                this.goodsForm.goods_id = this.goods_id;
                if (this.tabsActiveName == 1) {
                    if (this.goodsForm.spec_type == 10) {
                        if (!this.goodsForm.goods_price) {
                            this.$message.error("规格库存-请填写平台价");
                            return;
                        }
                        if (!this.goodsForm.market_price) {
                            this.$message.error("规格库存-请填写销售价");
                            return;
                        }
                        if (!this.goodsForm.stock_num) {
                            this.$message.error("规格库存-请填写库存");
                            return;
                        }
                    } else {
                        let skuList = this.skuData.skuList;
                        let specList = this.skuData.specList;
                        var specFlag = specList.every(function (a, b, c) {
                            return a.spec_name != '';
                        })
                        var valueFlag = specList.every(function (a, b, c) {
                            return a.valueList.length != 0;
                        })
                        if (!specFlag) {
                            this.$message.error('规格组名称不能为空！')
                            return;
                        }
                        console.log('valueFlag', valueFlag)
                        if (!valueFlag) {
                            this.$message.error('规格值名称不能为空！')
                            return;
                        }
                        if (this.skuData.skuList.length == 0) {
                            this.$message.error('请添加规格信息！')
                            return;
                        }
                        var goodsPriceFlag = skuList.every(function (a, b, c) {
                            return a.goods_price != '';
                        })
                        var marketPriceFlag = skuList.every(function (a, b, c) {
                            return a.market_price != '';
                        })
                        var unitFlag = skuList.every(function (a, b, c) {
                            return a.goods_unit != '';
                        })
                        if (!goodsPriceFlag) {
                            this.$message.error('请填写平台价！')
                            return;
                        }
                        if (!marketPriceFlag) {
                            this.$message.error('请填写商品销售价！')
                            return;
                        }
                        if (!unitFlag) {
                            this.$message.error('请填写商品单位！')
                            return;
                        }
                    }
                }
                submitApi = editGoods;
            } else {
                submitApi = addGoods;
            }
            this.isDisabled = true;
            this.isLoading = true;
            skuDataStr = JSON.stringify(this.skuData)
            const relationGoodsIds = this.relationGoods.map((v) => {
                return v.goods_id
            })
            this.goodsForm.rel_goods_id = relationGoodsIds.join(",");
            this.goodsForm.specData = skuDataStr;
            let res = await this.$getCsrToken();
            if (res.code == 0) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        submitApi(this.goodsForm).then((res) => {
                            if (res.code == 0) {
                                this.$message({
                                    message: res.msg,
                                    type: "success",
                                });
                                this.isDisabled = false;
                                this.isLoading = false;
                                this.$router.go(-1);
                            } else {
                                this.isDisabled = false;
                                this.isLoading = false;
                            }
                        });
                    } else {
                        this.isDisabled = false;
                        this.isLoading = false;
                        if (localStorage.getItem('X-Csrf-Token')) {
                            localStorage.setItem("X-Csrf-Token", '');
                        }
                        return false;
                    }
                });
            }
        },
        goBack() {
            this.$router.go(-1);
        },
    },
};
</script>
<style scoped>
/deep/ .el-table .cell {
    overflow: inherit;
}

.form-con {
    margin-top: 10px;
}

.titTip {
    font-size: 12px;
    color: #999;
}

.form-input {
    text-align: left;
}

.tip {
    font-size: 12px;
    color: red;
}

.spec-wrap {
    width: 460px;
    padding: 20px 10px 0 16px;
    border: 1px dotted rgba(0, 0, 0, 0.1);
    border-radius: 4px;
    background: #fbfbfb;
    margin-bottom: 20px;
    position: relative;
}

.spec-tags-item {
    margin-right: 4px;
    margin-bottom: 4px;
}

.del-btn {
    font-size: 20px;
    position: absolute;
    right: -10px;
    top: -16px;
}

.sku-list {
    /* margin-top: 20px; */
}

.sku-batch-title {
    font-size: 12px;
}

.sku-id {
    width: 130px;
}

.multiple-wrap {
    /* width: 880px; */
}

.upload-img-wrap {
    display: flex;
    flex-wrap: wrap;
}

.upload-img-item {
    position: relative;
    margin-right: 10px;
    margin-bottom: 10px;
}

.upload-img-item .close-icon {
    position: absolute;
    right: -6px;
    top: -6px;
    font-size: 18px;
}
</style>